package com.bsoft.hospitalchs.ui.childpicture;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.bsoft.hospitalchs.R;
import com.bsoft.hospitalchs.api.SimpleMyCallBack;
import com.bsoft.hospitalchs.base.BaseCommonPresenter;
import com.bsoft.hospitalchs.model.HttpExceptionBean;
import com.bsoft.hospitalchs.model.NOResultBean;
import com.bsoft.hospitalchs.model.PhotoResBean;
import com.bsoft.hospitalchs.model.PicResBean;
import com.bsoft.hospitalchs.model.PicSaveInfoBean;
import com.bsoft.hospitalchs.model.RecordInfo;
import com.bsoft.hospitalchs.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 泅渡者
 * Created on 2017/5/18.
 */

public class ChildpicturePresenter extends BaseCommonPresenter<ChildpictureContract.View> implements ChildpictureContract.Presenter {

    private HashMap<Integer, String> statueMap = new HashMap<>();//选中状态集合

    public ChildpicturePresenter(ChildpictureContract.View view, Context context) {
        super(view, context);
    }

    @Override
    public void toUpload(String path) {
        File file = new File(path);
        Log.d("FileSize", FormetFileSize(getFileSizes(file)));
        RequestBody photo = RequestBody.create(MediaType.parse("image/png"), file);
        Map<String, RequestBody> photos = new HashMap<>();
        photos.put("fileName\"; filename=\"icon.png", photo);
        mCompositeSubscription.add(apiImple.updateUser(photos).subscribe(newMySubscriber(new SimpleMyCallBack<PicResBean>() {
            @Override
            public void onError(HttpExceptionBean mHttpExceptionBean) {
                super.onError(mHttpExceptionBean);
                Log.e("faile", mHttpExceptionBean.toString());
                ToastUtils.showShort("网络异常.....");
            }

            @Override
            public void onNext(PicResBean str) {
                Log.e("success", str.toString());
                view.showUrl(str);
            }
        })));
    }

    @Override
    public void toSave(PicSaveInfoBean picSaveInfoBean) {

        mCompositeSubscription.add(apiImple.SavePicInfo(picSaveInfoBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onCompleted() {
                        Log.d("保存完成", "");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("保存失败", e.getMessage());
                        ToastUtils.showShort("网络异常.....");
                    }

                    @Override
                    public void onNext(JsonObject str) {
                        Gson gson = new Gson();
                        NOResultBean noResultBean = gson.fromJson(str, new TypeToken<NOResultBean>() {
                        }.getType());
                        if (noResultBean.getCode() == 200) {
                            // 创建构建器
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            // 设置参数
                            builder.setTitle(R.string.app_name).setIcon(R.mipmap.ic_launcher)
                                    .setMessage("保存成功！")
                                    .setNegativeButton("", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    }).create().show();
                        }
                    }
                }));


    }

    @Override
    public void guardianChange(CheckBox[] hashMap) {
        for (final CheckBox cb : hashMap) {
            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        statueMap.put(cb.getId(), cb.getText().toString());
                    } else {
                        statueMap.remove(cb.getId());
                    }

                }
            });

        }

    }

    /**
     * 获取照片记录信息
     */
    @Override
    public void getPhotoInfo(RecordInfo recordInfo) {
        mCompositeSubscription.add(apiImple.GetPhotoInfo(recordInfo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PhotoResBean>() {
                    @Override
                    public void onCompleted() {
                        Log.d("照片信息获取完成", "");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("照片信息获取失败", e.getMessage());
                    }

                    @Override
                    public void onNext(PhotoResBean str) {
                        if (str.getCode() == 200) {
                            view.ShowPhotoinfo(str);
                        }
                    }
                }));

    }

    /**
     * 返回拼接好的陪同人信息
     *
     * @return
     */
    @Override
    public String getStr() {
        if (statueMap.size() == 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Iterator iter = statueMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            sb.append(entry.getValue() + ",");
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

    public long getFileSizes(File f) {//取得文件大小
        long s = 0;
        try {

            if (f.exists()) {
                FileInputStream fis = null;

                fis = new FileInputStream(f);
                s = fis.available();
            } else {
                f.createNewFile();
                System.out.println("文件不存在");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    public String FormetFileSize(long fileS) {//转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
}
